package com.atguigu.gulimall.product.service.impl;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.es.Attrs;
import com.atguigu.gulimall.product.es.SkuEsModel;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SaveProductToEsFeignClient;
import com.atguigu.gulimall.product.feign.WareSkuFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareSkuFeignService wareSkuFeignService;
    @Autowired
    private SaveProductToEsFeignClient saveProductToEsFeignClient;
    @Autowired
    private SpuInfoDao spuInfoDao;
    @Override
    @Transactional
    public void spuinfoUp(Long spuId) {

        //就是构造一个放es的实体类对象
        List<SkuInfoEntity>skuInfoList=skuInfoService.getSkuInfoBySpuId(spuId);
        //拿到它是为了去调远程服务，检查这些sku是否还有库存
        List<Long> skuInfoIds = skuInfoList.stream().map((item) -> {
            return item.getSkuId();
        }).collect(Collectors.toList());
        //拿到该spu下的所有基本属性
        List<ProductAttrValueEntity>baseAttrs=productAttrValueService.getAttrsBySpuId(spuId);
       //拿到该spu下的基本属性的id
        List<Long> baseAttrIds = baseAttrs.stream().map((baseAttr) -> {
            return baseAttr.getAttrId();
        }).collect(Collectors.toList());
        //根据ids从属性表中拿到可以搜索的属性
        List<AttrEntity>attrsOfSearch=attrService.getAttrsOfSearchTpye(baseAttrIds,1L);
        //拿到该spu下看可以被搜索的基本属性id集合
        List<Long> baseAttrsOfSearchIds = attrsOfSearch.stream().map((obj) -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        //拿到了该spu下且支持搜索的属性和值  idset用于去重
        Set<Long> idSet = new HashSet<>(baseAttrsOfSearchIds);
        List<ProductAttrValueEntity> collect = baseAttrs.stream().filter((item) -> {
            return idSet.contains(item.getAttrId());
        }).collect(Collectors.toList());
        //attrsList被设置到skuEsModel.setAttrs(attrsList);
        List<Attrs> attrsList = collect.stream().map((item) -> {
            Attrs attr = new Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        Map<Long, Boolean> map =null;
        try {
            //就是为了拿到该spu下的sku们，每个是否有库存
            R r = wareSkuFeignService.checkSKusHasStock(skuInfoIds);
            //这步是创建了一个表示List<SkuStockVo>的对象
            TypeReference<List<SkuStockVo>> type = new TypeReference<List<SkuStockVo>>(){};
            //该sku对应的
            List<SkuStockVo> skuStockVoList = r.getData(type);
            //把skuId的值当做key把hasStock的值当做value 这点要学一下 把集合转成map的方式
            //把sku是否有库存的情况装转成一个Map
            map = skuStockVoList.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, skuStockVo -> skuStockVo.getHasStock()));
        }catch (Exception e){
             log.error("库存服务调用出现问题{}",e);
        }
        Map<Long, Boolean> map1 =map;
        List<SkuEsModel> skuEsModelList = skuInfoList.stream().map((item) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            BrandEntity brand = brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(category.getName());
            skuEsModel.setAttrs(attrsList);
            //这里没有设置销售属性
            //TODO 发送远程请求 确定hasStock和hotScore
            skuEsModel.setHotScore(0L);
            if (map1 ==null){
                skuEsModel.setHasStock(true);
            }else {
                Boolean hasStock = map1.get(item.getSkuId());
                skuEsModel.setHasStock(hasStock);
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        //然后就调用远程服务把商品数据放入es
        R r = saveProductToEsFeignClient.productUp(skuEsModelList);
        if (r.getCode()==0){
            //表示远程调用成功
            //第一步就是把spu的状态改一下，改成上架1
            spuInfoDao.updateByType(spuId,1);
        }else {
            log.error("远程接口存es数据失败在!");
        }
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<SpuInfoEntity> page = this.page(
//                new Query<SpuInfoEntity>().getPage(params),
//                new QueryWrapper<SpuInfoEntity>()
//        );
        //自己写的一个类，主要作用是params里面的分页数据封装到query对象里面去
        Query<SpuInfoEntity> query = new Query<>();
        //得到了一个分页对象，里面封装了当前页和每页记录数
        IPage<SpuInfoEntity> page = query.getPage(params);
        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key=(String)params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId =(String) params.get("brandId");
        //Long catelogId=(Long)params.get("catelogId");
        //Long brandId=(Long)params.get("brandId");
        Integer status=(Integer)params.get("status");
        String order=(String)params.get("order");
        if (StringUtils.isNotEmpty(key)){
            //(spuid=xx or spuname=xxx) 这里要用and
            //queryWrapper.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
            queryWrapper.and((obj)->{
                obj.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
            });
        }
        if (catelogId !=null){
            queryWrapper.and((obj)->{
                obj.eq(SpuInfoEntity::getCatalogId,catelogId);
            });
        }
        if (brandId !=null){
            queryWrapper.and((obj)->{
                obj.eq(SpuInfoEntity::getBrandId,brandId);
            });
        }
        if (status !=null){
            queryWrapper.and((obj)->{
                obj.eq(SpuInfoEntity::getPublishStatus,status);
            });
        }
        if (order !=null){
            if ("asc".equalsIgnoreCase(order)){
                queryWrapper.orderByAsc(SpuInfoEntity::getId);
            }
            if ("desc".equalsIgnoreCase(order)){
                queryWrapper.orderByDesc(SpuInfoEntity::getId);
            }
        }
        IPage<SpuInfoEntity> iPage = this.page(page, queryWrapper);
        return new PageUtils(iPage);
    }

    /**
     * 根据前端传过来的spu信息，保存到相应的表中
     * @param spuSaveVo
     */
    @Override
    @Transactional
    public void saveSpuDetails(SpuSaveVo spuSaveVo) {
        //保存spu基本信息，pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuInfo(spuInfoEntity);
        //保存spu的描述图片，pms_spu_info_desc，它保存的时候是图片路径分隔开用","
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //介绍图片可能有很多，这里把一个spu下的图片介绍放在了一条数据库记录里面，数据库里面用的是longtex类型
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.savespuInfoDesc(spuInfoDescEntity);
        //保存图片集 pms_spu_images 它是一个图片就要生成一个记录 这些是给sku选的图片
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImagesBySpuId(spuInfoEntity.getId(),images);
        //保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrsList = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrsList.stream().map((item) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attr = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attr.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setAttrSort(0);
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrs(collect);
        //spu商品购买后的成长积分，和购物积分
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.save(spuBoundTo);
        //保存当前sku对应的相关信息
        List<Skus> skusList = spuSaveVo.getSkus();
        //ArrayList<SkuInfoEntity> skuInfoList = new ArrayList<>();
            skusList.forEach((sku)->{
                List<Images> imagesList = sku.getImages();
                String defaultImage="";
                for (Images image : imagesList) {
                    if (image.getDefaultImg()==1){
                        defaultImage=image.getImgUrl();
                    }
                }
                //保存sku的基本信息，pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDesc("");
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //保存sku的图片信息,pms_sku_images
                if (imagesList !=null && imagesList.size()>0){
                    List<SkuImagesEntity> skuImageList = new ArrayList<>();
                    for (Images image : imagesList) {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgUrl(image.getImgUrl());
                        skuImagesEntity.setDefaultImg(image.getDefaultImg());
                        skuImagesEntity.setImgSort(0);
                        skuImageList.add(skuImagesEntity);
                    }
                    //要baoz该sku的图集不能为空
                     skuImageList = skuImageList.stream().filter((item) -> {
                        return StringUtils.isNotEmpty(item.getImgUrl());
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImageList);
                }
                //sku的销售属性，pms_sku_sale_attr_value
                List<Attr> attrList = sku.getAttr();
                if (attrList !=null && attrList.size()>0){
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueList = new ArrayList<>();
                    for (Attr attr : attrList) {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuSaleAttrValueList.add(skuSaleAttrValueEntity);
                    }
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
                }
                //sku的优惠卷，满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))==1
                || skuReductionTo.getMemberPrice() !=null){
                    //对于一个sku来说，你的买几件打几折，你的满多少减多少，你的会员减多少。但凡你满足其中一个条件你录了的都要调远程接口
                    couponFeignService.saveSkuReduction(skuReductionTo);
                }
            });

    }

    @Override
    public void saveSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

}